import importer
import db
import sys
import baostock as bs

def load(part, part_count):
    cursor_rs = importer.load_cursor()
    sharding_rs = load_range(part, part_count)
    clear_data = importer.build_sharding(cursor_rs, sharding_rs)
    for data in clear_data:
        importer.load_by_code(data)   

def load_range(range_index, range_count):
    countsql = "select count(*) as `count` from sharding"
    with db.UsingMysql() as um:
        um.cursor.execute(countsql);
        count_rs = um.cursor.fetchone()
        count = int(count_rs["count"])
        index = int(range_index)
        size = int(count/range_count)
        sql = "select * from sharding "
        sql += " order by stock_code asc limit %s,%s;"
        params = ((index-1)*size, size)
        um.cursor.execute(sql, params);
        rs = um.cursor.fetchall()
        return rs          


if __name__ == '__main__':
    args = ""
    if len(sys.argv) > 1:
        args = sys.argv[1]
    part = 0
    part_count = 0
    if args != "":
        argArrary = args.split('/')
        part = int(argArrary[0]) 
        part_count = int(argArrary[1]) 
    bs.login()
    load(part, part_count)
    bs.logout()